<!--
* @author luguoxiang
* @date 2021-09-07
* 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <t-form
    ref="form"
    :class="['item-container', `login-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <template v-if="type === 'password'">
      <t-form-item name="account">
        <t-input v-model="formData.account" size="large" clearable placeholder="请输入账号：admin">
          <template #prefix-icon>
            <t-icon name="user" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="password">
        <t-input
          v-model="formData.password"
          size="large"
          :type="showPsw ? 'text' : 'password'"
          clearable
          placeholder="请输入登录密码：123456"
        >
          <template #prefix-icon>
            <t-icon name="lock-on" />
          </template>
          <template #suffix-icon>
            <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item v-if="captchaFlag" name="captcha">
        <t-input v-model="formData.captcha" size="large" placeholder="验证码">
          <template #prefix-icon>
            <t-icon name="lock-on" />
          </template>
          <template #suffix>
            <img class="inner-img" :src="captchaImg" @click="getCaptcha()" />
          </template>
        </t-input>
      </t-form-item>

      <div class="check-container remember-pwd">
        <t-checkbox v-model="formData.rememberMe">{{ $t('七天免登录') }}</t-checkbox>
        <span class="tip">忘记账号？</span>
      </div>
    </template>

    <!-- 扫码登陆 -->
    <template v-else-if="type == 'qrcode'">
      <div class="tip-container">
        <span class="tip">使用移动端扫一扫登录</span>
        <span class="refresh" @click="generateQrcode">刷新 <t-icon name="refresh" /> </span>
      </div>
      <qrcode-vue :value="qrcode" :size="192" level="H" />
    </template>

    <!-- 手机号登陆 -->
    <template v-else>
      <t-form-item name="phone">
        <t-input v-model="formData.phone" size="large" placeholder="请输入手机号码">
          <template #prefix-icon>
            <t-icon name="mobile" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item class="verification-code" name="captcha">
        <t-input v-model="formData.captcha" size="large" placeholder="请输入验证码" />
        <t-button variant="outline" :disabled="countDown > 0" @click="sendCode">
          {{ countDown == 0 ? '发送验证码' : `${countDown}秒后可重发` }}
        </t-button>
      </t-form-item>
    </template>

    <t-form-item v-if="type !== 'qrcode'" class="btn-container">
      <t-button :loading="loading" block size="large" type="submit"> 登录 </t-button>
    </t-form-item>

    <div class="switch-container">
      <span v-if="type !== 'password'" class="tip" @click="switchType('password')">使用账号密码登录</span>
      <span v-if="type !== 'qrcode'" class="tip" @click="switchType('qrcode')">使用扫码登录</span>
      <span v-if="type !== 'phone'" class="tip" @click="switchType('phone')">使用手机号登录</span>
    </div>
  </t-form>
</template>

<script setup lang="ts">
import './index.less';
import { onMounted, ref } from 'vue';
import QrcodeVue from 'qrcode.vue';
import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next';
import { useCounter } from '@/hooks';
import { useAccountStore } from '@/store';
import * as commonApi from '@/api/common';
import * as codeLoginApi from '@/api/codeLogin';
import * as loginApi from '@/api/login';
import configApi from '@/api/sysConfig';

const accountStore = useAccountStore();

const INITIAL_DATA = {
  phone: '',
  account: import.meta.env.VITE_LOGIN_ACCOUNT,
  password: import.meta.env.VITE_LOGIN_PASSWORD,
  captcha: '',
  checked: false,
  rememberMe: false,
};

const FORM_RULES: Record<string, FormRule[]> = {
  phone: [{ required: true, message: '手机号必填', type: 'error' }],
  account: [{ required: true, message: '账号必填', type: 'error' }],
  password: [{ required: true, message: '密码必填', type: 'error' }],
  captcha: [{ required: true, message: '验证码必填', type: 'error' }],
};

const emits = defineEmits(['ok']);
const type = ref('password');

const form = ref<FormInstanceFunctions>();
const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);
const loading = ref(false);

const [countDown, handleCounter] = useCounter();

const captchaFlag = ref(false);
const captchaImg = ref('');

let timer = -1;
const switchType = (val: string) => {
  clearInterval(timer);
  type.value = val;
  if (val === 'qrcode') {
    generateQrcode();
  }
};

function getCaptcha() {
  commonApi.captcha('login').then((res) => {
    captchaImg.value = res;
  });
}

/**
 * 发送验证码
 */
const sendCode = () => {
  form.value.validate({ fields: ['phone'] }).then((e) => {
    if (e === true) {
      handleCounter();
    }
  });
};

const onSubmit = async ({ validateResult }) => {
  if (validateResult === true) {
    try {
      loading.value = true;
      await accountStore.login({ ...formData.value });
      emits('ok');
    } catch (e) {
      console.error(e);
      loading.value = false;
      getCaptcha();
    }
  }
};

configApi.get('login').then((res) => {
  captchaFlag.value = res.captcha;
  if (res.captcha) {
    getCaptcha();
  }
});

const qrcode = ref('');
function generateQrcode() {
  codeLoginApi.generateCode().then((res) => {
    qrcode.value = `$qrauth:${res}`;
    clearInterval(timer);
    timer = setInterval(() => {
      loginApi.codeLogin(res).then(() => {
        clearInterval(timer);
        emits('ok');
      });
    }, 2000);
  });
}
</script>
<style lang="less" scoped>
.inner-img {
  height: var(--td-comp-size-xl);
}
</style>
